<template>
    <div class="activityListEdit">
        <!-- <div class="main-title">
            <h4 v-text="this.$route.query.id !== ''? '活动编辑' : '活动新建'"></h4>
            <div class="btn-box">
                <el-button class="filter-item" type="success" :loading="btnLoading" @click="save">保存</el-button>
                <el-button class="filter-item" type="primary" plain @click="$router.back()">返回</el-button>
            </div>
        </div> -->
        <section class="activitySection">
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick" class="activitytab">
                 <el-tab-pane label="基本信息" name="1">                    
                    <div class="block-header"><div>活动规则</div></div>
                    <el-form :model="templateMnDTO"  size="medium" ref="form2" label-width="150px">
                    <div class="block-content">
                        <el-form-item label="购买商品件数:" prop="goodsNum" :rules="commonRules.numberRule">
                            <el-input v-model="templateMnDTO.goodsNum" placeholder="购买商品件数" ></el-input>
                        </el-form-item>
                        <el-form-item label="兰蜜价:" prop="lanPrice" :rules="commonRules.priceRule">
                            <el-input type="text" v-model="templateMnDTO.lanPrice"  @change="calcPrice" placeholder="请输入兰蜜价"></el-input>
                        </el-form-item>
                        <el-form-item label="大区价:" prop="regionPrice">
                            <el-input type="text" v-model="templateMnDTO.regionPrice"  placeholder="自动生成" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="董事价:" prop="directorPrice">
                            <el-input type="text" v-model="templateMnDTO.directorPrice"  placeholder="自动生成" :disabled="true"></el-input>
                        </el-form-item>
                        
                        <el-form-item label="最高佣金:" :rules="commonRules.priceRule">
                            <el-input type="text"  placeholder="请输入最高佣金" @change="calcPrice" v-model="templateMnDTO.commission"></el-input>
                        </el-form-item>
                    </div>
                    </el-form>
                    <el-button type="success" @click="save" :loading="btnLoading" class="savebtn">保存</el-button>
                     <el-button class="filter-item" type="primary" plain @click="$router.push({name:'activityList'})">返回</el-button>
                 </el-tab-pane>
                <el-tab-pane label="活动商品" name="2">
                    <div class="block-header"><div>活动商品</div></div>
                    <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseGoods">添加商品</el-button>
                    <el-form :model="form" size="medium" ref="form" label-width="0px">
                        <el-table :data="form.welfareGoodsList" v-loading="listLoading" element-loading-text="给我一点时间">                      
                            <el-table-column align="center" label="商品">
                                <template slot-scope="scope">
                                    <img :src="scope.row.majorPic" class="majorPicImg"  />
                                    <div class="div1">
                                        <div>
                                            款号：{{scope.row.goodsSn}}
                                        </div>
                                        <div>
                                            商品名称：{{scope.row.goodsTitle}}
                                        </div> 
                                    </div>    
                                </template>
                            </el-table-column>                    
                            <!-- <el-table-column align="center" label="是否显示" width="200px">
                                <template slot-scope="scope">
                                    <el-switch
                                        v-model="scope.row.enable"
                                        active-color="#13ce66"
                                        inactive-color="#ff4949"
                                        :active-value="true"
                                        :inactive-value="false"
                                        @change="updateEnable(scope.row)"
                                        >
                                    </el-switch>
                                </template>
                            </el-table-column> -->
                            <el-table-column align="center" label="操作" width="220" fixed="right">
                                <template slot-scope="scope">
                                    <el-button v-if="rightsButtons['sku']" type="primary" size="mini" @click="lookSku(scope.row.id)" >查看</el-button>
                                    <el-button type="primary" size="mini" v-show="scope.row.enable===false" @click="deleteGood(scope.row.goodsId)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>                     
                    </el-form>
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page.sync="listQuery.pageNo"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="listQuery.pageSize"
                        background
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="listTotal">
                    </el-pagination>   
                </el-tab-pane>
                <el-tab-pane label="H5自定义" name="3">  
                    <activity-h5-detail :activeName="activeName"></activity-h5-detail>
                 </el-tab-pane>   
            </el-tabs>  
        </section>        
    </div>
</template>

<script>
import differenceBy from 'lodash/differenceBy'
import ActivityH5Detail from './detail'
export default {
    name: 'activityListEdit',
    components: {
        ActivityH5Detail
    },
    data(){
        return {
            activeName:'1',
            templateMnDTO:{
                directorPrice:'',
                firstFreight:'0',
                lanPrice:'',
                goodsNum:'',
                regionPrice:'',
                secondFreight:'0',
                commission:'',
                id:''
            },
            btnLoading:false,
            listLoading: false,
            listTotal: 0,
            form: {
                welfareGoodsList: [],
                goodsAttr: [],
            },
            listQuery:{
                pageNo: 1,
                pageSize: 10,
                promotionId: this.$route.query.id
            }
        }
    },
    mounted(){
        if(this.$route.query.id){
            this.getTemplateMnDTO()
            this.getGoodsDTO()                          
        } else {
            this.templateMnDTO={
                directorPrice:'',
                firstFreight:'0',
                lanPrice:'',
                goodsNum:'',
                regionPrice:'',
                secondFreight:'0',
                id:''
            }
        }    
    },
    beforeRouteEnter(to, from, next) {  
        next(vm => {
            if(from.name==='goodsSku'){
                var goodsQuery = JSON.parse(localStorage.getItem('activityListEdit'))
                vm.activeName='2'
                vm.listQuery=goodsQuery
                vm.getGoodsDTO()    
            }
        })
    },
    methods:{
        handleClick(){
            // if(this.activeName==='2'){
            //     this.getGoodsDTO()
                
            // }  
            console.log(this.activeName)  
        },
        calcPrice(){
            let query = {
            lmPrice: this.templateMnDTO.lanPrice,
            highestCommission: this.templateMnDTO.commission
            };
            this.calcRDPrice(query, (data) => {
                this.templateMnDTO.regionPrice = data.regionPrice;
                this.templateMnDTO.directorPrice = data.directorPrice;
            });
        },
        chooseGoods() {
            let selected= this.form.welfareGoodsList.map(i => {
                return {
                    goodsId: i.goodsId,
                    name: i.goodsTitle
                }
            })
            this.goodsChoose({}, selected).then(val => {
                let goodsList = this.form.welfareGoodsList
                let needDelGoods = differenceBy(goodsList, val, 'goodsId');
                let needAddGoods = differenceBy(val, goodsList, 'goodsId');
                let goodsIdList=[]
                let deleteGoodsIdList=[]
                console.log(needAddGoods)
                console.log(needDelGoods)
                needAddGoods.map((item) => {
                    goodsIdList.push(item.goodsId)                 
                })
                needDelGoods.map((item) =>{
                    deleteGoodsIdList.push(item.goodsId)
                })
                if (goodsIdList.length) {
                    this.request({
                        url: '/promotion/goods/batch',
                        method: 'post',
                        data: {
                            goodsIdList:goodsIdList,
                            promotionId: this.$route.query.id
                        }
                    }).then((res) => {
                        if(res.data==true){
                            this.$message({
                                message: '添加成功',
                                type: 'success'
                            })
                            this.getGoodsDTO()  
                        }else{
                           this.$message({
                                message: '添加失败',
                                type: 'error'
                            }) 
                        }                            
                    }).catch(err => {
                        console.log(err);
                    });
                }
                if(deleteGoodsIdList.length){
                    this.request({
                        url: '/promotion/goods/batch',
                        method: 'delete',
                        data: {
                            goodsIdList:deleteGoodsIdList,
                            promotionId: this.$route.query.id
                        }
                    }).then((res) => {
                        if(res.data==true){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            })
                            this.getGoodsDTO()  
                        }else{
                           this.$message({
                                message: '删除失败',
                                type: 'error'
                            }) 
                        }                            
                    }).catch(err => {
                        console.log(err);
                    });
                }
            }).catch(err => {
                this.form.welfareGoodsList = this.form.welfareGoodsList.filter(item => item.type !==1);
            });
        },
        getTemplateMnDTO(){
            this.request({
                url: '/promotion/template-mn/'+this.$route.query.id,
                method: 'get'
            }).then(({data}) => {
                if(data!==null){
                    this.templateMnDTO=data
                } else {
                     this.templateMnDTO={
                        directorPrice:'',
                        firstFreight:'',
                        lanPrice:'',
                        materialNum:'',
                        regionPrice:'',
                        secondFreight:'',
                        id:''
                    }
                }
            }).catch(err => {
                console.log(err);
            }); 
        },
        getGoodsDTO() {
            this.listLoading=true
            this.request({
                url: '/promotion/goods',
                method: 'get',
                params: this.listQuery
            }).then(({data}) => {
                this.listLoading=false
                if(data!==null){
                    this.listTotal=data.total
                    this.form.welfareGoodsList=data.records                 
                } else {
                     this.form.welfareGoodsList=[]
                }
            }).catch(err => {
                console.log(err);
                 this.listLoading=false
            }); 
        },
        handleSizeChange (value) {
          this.listQuery.pageSize = value;
          this.getGoodsDTO()
        },
        handleCurrentChange(page) {
          this.listQuery.pageNo = page;
          this.getGoodsDTO();
        },
        save() {
            this.$refs.form2.validate(valid => {
                if (!valid) {
                    return false
                }
                this.request({
                    url: '/promotion/template-mn/'+this.$route.query.id,
                    method: 'put',
                    data: this.templateMnDTO
                }).then((res) => {
                    if(res.data===true) {
                        this.$message({
                            message: '保存成功',
                            type: 'success'
                        })
                    }else {
                        this.$message({
                            message: '保存失败',
                            type: 'error'
                        })
                    } 
                }).catch(err => {
                    console.log(err)
                })
            })
        },
        updateEnable(enable) {
            this.request({
                url: '/promotion/goods/'+ enable.id,
                method: 'put',
                data: enable
            }).then((res) => {
                console.log(res)
                if(res.data===true) {
                    this.$message({
                        message: '设置成功',
                        type: 'success'
                    })
                }else {
                    this.$message({
                        message: '设置失败',
                        type: 'error'
                    })
                } 
            }).catch(err => {
                console.log(err)
            })
        },
        deleteGood(id) {
            this.request({
                url: '/promotion/goods/batch',
                method: 'delete',
                data: {
                    goodsIdList:[id],
                    promotionId: this.$route.query.id}
                }).then((res) => {
                    if(res.data==true){
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        this.getGoodsDTO()  
                    }else{
                        this.$message({
                            message: '删除失败',
                            type: 'error'
                        }) 
                    }                            
                }).catch(err => {
                    console.log(err);
                })
            // this.request({
            //     url: '/promotion/goods/'+ id,
            //     method: 'delete'
            // }).then((res) => {
            //     console.log(res)
            //     if(res.data===true) {
            //         this.$message({
            //             message: '删除成功',
            //             type: 'success'
            //         })
            //         this.getGoodsDTO()
            //     }else {
            //         JSON
            //         this.$message({
            //             message: '删除失败',
            //             type: 'error'
            //         })
            //     } 
            // }).catch(err => {
            //     console.log(err)
            // })
        },
        lookSku(id) {
            localStorage.setItem('activityListEdit', JSON.stringify(this.listQuery))
            this.$router.push({ path: '/activity/goodsSku', query: { id: id} })
        }
    }
}
</script>

<style lang="scss" scoped>
    .majorPicImg{
        width: 100px;
        height: 100px;
        float: left;
    }
    .div1{
        height: 100px;
        float: left;
        line-height: 50px;
        text-align: left;
        margin-left:20px; 
    }
    .block-header{
        color: #1ea0ff;
        font-size: 14px;
        padding: 12px 0;
        margin-bottom: 12px;
        background: #f7f7f7;
        &>div{
            padding: 0 12px;
            border-left: 2px solid #1ea0ff;
        }
    }
    .activitySection{
        padding: 20px;
        .savebtn{
            margin: 30px 0 0 150px;
        }
    }
    .activityListEdit .activitySection {
        background-color: #fff!important;
    }
</style>
